#include "ModifyConstructWidget.h"
#include "ui_ModifyConstructWidget.h"
#include "../database/DatabaseManager.h"
#include <QMessageBox>

ModifyConstructWidget::ModifyConstructWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ModifyConstructWidget)
{
    ui->setupUi(this);
}

ModifyConstructWidget::~ModifyConstructWidget()
{
    delete ui;
}

void ModifyConstructWidget::init()
{
    DatabaseManager &manager = DatabaseManager::getInstance();
    QSqlDatabase db = manager.m_database;

    if (!db.isOpen()) {
        qWarning() << "数据库未连接";
        return;
    }

    QSqlQuery q(db);
    // 如果列名是 code，请把 mould_code 改为 code
    q.prepare("SELECT id, mould_code FROM Mould ORDER BY mould_code COLLATE NOCASE");
    if (!q.exec()) {
        qWarning() << "查询失败:" << q.lastError().text();
        return;
    }
    QSignalBlocker blocker(ui->comboBox);
    ui->comboBox->clear();
    while (q.next()) {
        const int id = q.value(0).toInt();
        const QString name = q.value(1).toString();
        ui->comboBox->addItem(name, id);               // 文本显示 name，userData 存 id
    }

    // 可选：默认不选中任何项
    ui->comboBox->setCurrentIndex(-1);
}

void ModifyConstructWidget::on_comboBox_currentIndexChanged(int index)
{
    DatabaseManager &manager = DatabaseManager::getInstance();
    QSqlDatabase db = manager.m_database;
    ui->lineEdit_cid->setReadOnly(true);
    if (!db.isOpen()) {
        qWarning() << "数据库未连接";
        return;
    }
    const int mouldId = ui->comboBox->currentData().toInt(); // addItem(name, id) 存的 id
    if (mouldId <= 0) {
        ui->lineEdit_cid->clear();
        ui->lineEdit_upper->clear();
        ui->lineEdit_lower->clear();
        // ui->lineEdit_upper_block->clear();
        // ui->lineEdit_lower_block->clear();
        return;
    }

    QSqlQuery q(db);
    q.prepare(R"(
    SELECT
        c.id,
        c.construction_id,
        COALESCE(su.sideplate_code, '') AS upper_code,
        COALESCE(sl.sideplate_code, '') AS lower_code,
        COALESCE(bu.block_code, '')     AS upper_block_code,
        COALESCE(bl.block_code, '')     AS lower_block_code
    FROM Construction c
    JOIN Mould m           ON m.id = c.mould_id
    LEFT JOIN SidePlate su ON su.id = m.upper_id
    LEFT JOIN SidePlate sl ON sl.id = m.lower_id
    LEFT JOIN Block bu     ON bu.id = c.upper_block_id
    LEFT JOIN Block bl     ON bl.id = c.lower_block_id
    WHERE c.mould_id = ?
    ORDER BY c.construction_id COLLATE NOCASE
)");
    q.addBindValue(mouldId);

    if (!q.exec()) {
        qWarning() << "[SQL FAIL]" << q.lastError().text()
        << " sql=" << q.lastQuery()
        << " bound=" << q.boundValues().size();
        return;
    }

    if (q.next()) {
        ui->lineEdit_cid->setText(         q.value(1).toString()); // construction_id
        // ui->lineEdit_upper->setText(       q.value(2).toString()); // upper sideplate_code
        // ui->lineEdit_lower->setText(       q.value(3).toString()); // lower sideplate_code
        _upper_sidePane_code = q.value(2).toString();
        _lower_sidePane_code = q.value(3).toString();
        // ui->lineEdit_upper_block->setText( q.value(4).toString()); // upper block_code
        // ui->lineEdit_lower_block->setText( q.value(5).toString()); // lower block_code
    } else {
        ui->lineEdit_cid->clear();
        ui->lineEdit_upper->clear();
        ui->lineEdit_lower->clear();
        // ui->lineEdit_upper_block->clear();
        // ui->lineEdit_lower_block->clear();
        _lower_sidePane_code.clear();
        _upper_sidePane_code.clear();
        qDebug() << "未找到该 mould_id 的 Construction 记录";
    }

    // 2) 查询并填充该模具关联的 blocks -> comboBox_2 / comboBox_3
    {
        QSqlQuery q(db);
        q.prepare(R"(
            SELECT b.id, b.block_code
            FROM MouldBlock mb
            JOIN Block b ON b.id = mb.block_id
            WHERE mb.mould_id = ?
            ORDER BY b.block_code COLLATE NOCASE
        )");
        q.addBindValue(mouldId);

        if (!q.exec()) {
            qWarning() << "查询 Blocks 失败:" << q.lastError().text();
            // 清空以免显示旧数据
            QSignalBlocker b2(ui->comboBox_2);
            QSignalBlocker b3(ui->comboBox_3);
            ui->comboBox_2->clear();
            ui->comboBox_3->clear();
            ui->comboBox_2->setCurrentIndex(-1);
            ui->comboBox_3->setCurrentIndex(-1);
            return;
        }

        QSignalBlocker b2(ui->comboBox_2);
        QSignalBlocker b3(ui->comboBox_3);
        ui->comboBox_2->clear();
        ui->comboBox_3->clear();

        //（可选）添加一个空项作为“未选择”
        // ui->comboBox_2->addItem(tr("-- 请选择 --"), QVariant());
        // ui->comboBox_3->addItem(tr("-- 请选择 --"), QVariant());

        while (q.next()) {
            const int blockId = q.value(0).toInt();
            const QString blockCode = q.value(1).toString();
            ui->comboBox_2->addItem(blockCode, blockId);
            ui->comboBox_3->addItem(blockCode, blockId);
        }

        // 默认不选中（按需改成 0）
        ui->comboBox_2->setCurrentIndex(-1);
        ui->comboBox_3->setCurrentIndex(-1);
    }

}


void ModifyConstructWidget::on_pushButton_clicked()
{
    if (ui->lineEdit_lower->text() != _lower_sidePane_code || ui->lineEdit_upper->text() != _upper_sidePane_code) {
        QMessageBox::critical(this, tr("错误"), tr("扫描的上下侧板编号与数据库中不一致"));
        return;
    }
    const int mouldId          = ui->comboBox->currentData().toInt();
    const QString construction = ui->lineEdit_cid->text().trimmed();
    const int upBlock = ui->comboBox_2->currentData().toInt();
    const int lowBlock = ui->comboBox_3->currentData().toInt();
    // const QString upBlock      = ui->lineEdit_upper_block->text().trimmed();
    // const QString lowBlock     = ui->lineEdit_lower_block->text().trimmed();

    if (mouldId <= 0 || construction.isEmpty()) {
        QMessageBox::warning(this, tr("提示"), tr("请选择模具并填写施工编号。"));
        return;
    }

    auto &mgr = DatabaseManager::getInstance();
    QSqlDatabase db = mgr.m_database;
    if (!db.isOpen()) { QMessageBox::critical(this, tr("错误"), tr("数据库未连接")); return; }

    if (!db.transaction()) { QMessageBox::critical(this, tr("错误"), tr("开启事务失败：%1").arg(db.lastError().text())); return; }

    QSqlQuery q(db);
    q.prepare(R"(
        UPDATE Construction
           SET upper_block_id = :up,
               lower_block_id = :low
         WHERE mould_id = :mid AND construction_id = :cid
    )");
    q.bindValue(":up",  upBlock);
    q.bindValue(":low", lowBlock);
    q.bindValue(":mid", mouldId);
    q.bindValue(":cid", construction);

    if (!q.exec()) {
        db.rollback();
        QMessageBox::critical(this, tr("错误"), tr("更新失败：%1").arg(q.lastError().text()));
        return;
    }
    if (q.numRowsAffected() == 0) {
        db.rollback();
        QMessageBox::warning(this, tr("未找到"),
                             tr("未找到 mould_id=%1, construction_id=%2 的记录。")
                                 .arg(mouldId).arg(construction));
        return;
    }
    if (!db.commit()) { db.rollback(); QMessageBox::critical(this, tr("错误"), tr("提交失败：%1").arg(db.lastError().text())); return; }

    QMessageBox::information(this, tr("成功"), tr("已更新施工记录。"));
}

